//
//  UIViewController+SelectVideo.swift
//  UGImage
//
//  Created by mac on 2022/12/5.
//

import Foundation
import UIKit
import TZImagePickerController
import AVFAudio
import AVKit

public extension UIViewController{
        func ug_selectVideo(config: ((TZImagePickerController)  ->  ())? = nil,
                             finish:@escaping (UIImage?,String?,Error?)->()
        ){
    
    
            let tzImagePicker = TZImagePickerController()
            tzImagePicker.allowPickingImage = false
            tzImagePicker.allowTakeVideo = true
            tzImagePicker.allowPickingVideo = true
            tzImagePicker.didFinishPickingVideoHandle = ({ coverImage, phasset in
                guard let phasset = phasset else{
                    let error = UGImageError( code: -1, msg: "未选中视频")
                    finish(nil,nil,error)
                    return
                }
        
                let options = PHVideoRequestOptions()
                options.version = .original
                options.deliveryMode = .automatic
                options.isNetworkAccessAllowed = true
                PHImageManager.default().requestAVAsset(forVideo: phasset, options: nil) { avasset, audioMix, info in
                    DispatchQueue.main.async {
                        guard let avasset = avasset else{
                          
                            let error = UGImageError(code: -1, msg: "视频获取为空")
                            finish(nil,nil,error)
                            return
                        }
    
                        avasset.toMp4 { avasset, error in
                            
                            finish(coverImage,avasset,nil)
                        }
                    }
                }
            })
    
            if let configBlock = config{
                configBlock(tzImagePicker)
            }
    
    
            tzImagePicker.modalPresentationStyle = .fullScreen
            self.present(tzImagePicker, animated: true, completion: nil)
    
        }
        
        
}
